package com.youlian.cloud.log.asepct;

import com.alibaba.fastjson.JSON;
import com.dianping.cat.Cat;
import com.dianping.cat.message.Transaction;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;

/**
 * DAO层执行拦截器
 *
 * @author : liukx
 * @create : 2018/7/4 14:38
 * @email : liukx@elab-plus.com
 */
public class CatDaoAscept {
    private final Logger logger = LoggerFactory.getLogger(CatAspect.class);

    public static String logOut(String str) {
        if (StringUtils.isEmpty(str)) {
            return "null";
        }

        if (str.length() > 500) {
            return str.substring(0, 500) + " 省略...";
        }

        return str;
    }

    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Transaction transaction = null;
        Object proceed = null;
        try {
            MethodSignature joinPointObject = (MethodSignature) pjp.getSignature();
            Method method = joinPointObject.getMethod();

            // 获取参数的名称
            Class<?>[] par = ((MethodSignature) pjp.getSignature()).getParameterTypes();
            String methodName = pjp.getSignature().getName();
            Class<?> classTarget = pjp.getTarget().getClass();
            Method objMethod = classTarget.getMethod(methodName, par);

            transaction = Cat.getProducer().newTransaction("SQL.Method", classTarget.getName().concat(".").concat(objMethod.getName()));
            logger.debug(" 开始执行方法 " + method.getName() + " 参数:" + logOut(JSON.toJSONString(pjp.getArgs())));
            proceed = pjp.proceed();
            if (proceed != null) {
                logger.debug("结束执行方法 " + method.getName() + " 参数值 : " + logOut(JSON.toJSONString(proceed)));
            } else {
                logger.debug(" 结束执行方法 ... " + method.getName());
            }
            transaction.setStatus(Transaction.SUCCESS);
        } finally {
            long start = System.currentTimeMillis();
            transaction.complete();
            long time = System.currentTimeMillis() - start;
            logger.info(" CAT DAO 拦截器事物提交时间 : " + time);
        }
        return proceed;
    }
}
